package com.zyh.utils;

import java.util.Random;
import java.util.concurrent.Semaphore;

/**
 * @Author zyh
 * @Date 2024/8/9 10:37
 * @Description 信号量 模拟停车
 */

public class SemaphoreDemo1 {
    public static void main(String[] args) {
        //创建停车任务
        Runnable task = new Runnable() {
            //创建信号量
            Semaphore semaphore = new Semaphore(3);
            @Override
            public void run() {
                //获取信号量，进入停车场
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //获取拿到信号量的当前系统时间
                long start = System.currentTimeMillis();
                System.out.println(Thread.currentThread().getName() + "进入停车场");
                //模拟停车时间
                try {
                    Thread.sleep(new Random().nextInt(2001) + 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //停车结束，释放信号量
                System.out.println(Thread.currentThread().getName() + "离开停车场");
                semaphore.release();
                //获取释放信号量的时间
                long end = System.currentTimeMillis();
                long l = end - start;
                System.out.println(Thread.currentThread().getName()+"停车"+l+"秒");
            }
        };
        //创建10个车辆线程
        for (int i = 1; i <= 10; i++) {
            new Thread(task, "车辆" + i).start();
        }
    }
}
